﻿package labox.innovation.gameserver.model.actor.position;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;

/**
 * 玩家位置处理类
 */
public final class PcPosition extends CharPosition {

	private static final Logger _log = LoggerFactory.getLogger(PcPosition.class.getName());

	private int _clientPreX;

	private int _clientPreY;

	private byte _warningCount;

	private int _distanceX;

	private int _distanceY;

	private long _distanceTime;

	private byte _abnormalCounter;

	// =========================================================
	// Constructor
	public PcPosition(FuzePcInstance activeObject) {
		super(activeObject);
	}

	public FuzePcInstance getActiveObject() {
		return (FuzePcInstance) _activeObject;
	}

	public void setXY(int x, int y, long time) {
		FuzePcInstance pc = getActiveObject();
		//如果不是GM，进行加速检测
		if (!pc.getAccessLevel().isGm()) {
			int desX = Math.abs(x - _clientPreX);
			int desY = Math.abs(y - _clientPreY);
			_clientPreX = x;
			_clientPreY = y;

			int speed = pc.getRunSpeed() * 10;
			int dis = speed + speed;
			if (desX > dis || desY > dis || desX + desY > dis) {
				_abnormalCounter++;
				if (_abnormalCounter > 6) {
					_log.info("加速检测激活:强迫下线", pc.getObjectId(), pc.getName());
					pc.getClient().closeNow();
				}
			}

			desX = Math.abs(x - _distanceX);
			desY = Math.abs(y - _distanceY);

			if (desX > speed || desY > speed || desX + desY > speed) {
				long interval = time - _distanceTime;

				if (interval < 20L) {
					_abnormalCounter = 0;
					_warningCount = 0;
				} else if (interval < 300L) {
					_abnormalCounter += 2;
				} else if (interval < 1400L) {
					_abnormalCounter += 1;
				} else {
					_abnormalCounter = 0;
				}

				if (_abnormalCounter > 6) {
					_log.info("加速检测激活:强迫下线", pc.getObjectId(), pc.getName());
					pc.getClient().closeNow();
					return;
				} else if (_abnormalCounter > 2) {
					if (_warningCount > 1) {
						_log.info("加速检测激活:强迫下线", pc.getObjectId(), pc.getName());
						pc.getClient().closeNow();
						return;
					}
					pc.sendMessage("请不要使用外挂或非官方的程序，如有疑问请联系GM!");
					_warningCount++;
				}

				_distanceTime = time;
				_distanceX = x;
				_distanceY = y;
			}
		}

		super.setXY(x, y);
	}

	public void reset() {
		_clientPreX = getX();
		_clientPreY = getY();
		_distanceX = getX();
		_distanceY = getY();
		_distanceTime = 0;
	}

	@Override
	protected void badCoords() {
		getActiveObject().teleToLocation(0, 0, 0);
		getActiveObject().sendMessage("Error with your coords, Please ask a GM for help!");
	}
}
